﻿package com.gobang.netmode.clientdata;

import java.net.Socket;

import com.gobang.gobangui.PlayFrame;
import com.gobang.gobangui.MainWindowUI;
import com.gobang.netmode.search.SearchJFrameOfLAN;
import com.gobang.netmode.search.SearchJFrameOfWAN;
import com.gobang.netmode.sendandreceive.Message;
import com.gobang.netmode.sendandreceive.MessageMSG;
import com.gobang.netmode.sendandreceive.Order;
import com.gobang.netmode.sendandreceive.SendAndReceive;
import com.gobang.netmode.util.ClientDataClass;
import com.gobang.netmode.util.Netmode;
import com.gobang.util.playeraction.CommonAction;
import com.gobang.util.playeraction.CompetitorAction;
import com.gobang.util.playeraction.RoomOwnerAction;
import com.gobang.util.uipattern.MyDialog;

public class ClientReceiveThread extends Thread {
	SendAndReceive sendAndReceive;
	Message message = new Message();
	public static PlayFrame playFrame = null;
	
	

	public ClientReceiveThread(SendAndReceive sendAndReceive) {
		this.sendAndReceive = sendAndReceive;
		playFrame = new PlayFrame();
		playFrame.setVisible(true);
	}

	public static PlayFrame getPlayFrame() {
		return playFrame;
	}

	public void run() {
		while (playFrame.isVisible()) {
			while (ChessClient.getIsWork()) {
				try {
					System.err.println("ClientReceiveThread.run()开始接收信息， 时间"+System.currentTimeMillis());
					message =sendAndReceive.receiveMessage();
					if (message != null) {
						System.err.println("ClientReceiveThread.run()" + message);
						this.message = analysisMessage(message);// 解析对象输入流
						if (message.order != Order.NULL) {
							clientOperation(message);
						}
					} else {
						System.err.println("ClientReceiveThread.run() message==null");
						ChessClient.setIsWork(false);
						playFrame.showNoticeIntable("与服务断开连接……", "通知");
					}
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			} // while (ChessClient.getIsWork()) end
			try {
				Thread.sleep(5000);// 无法连接服务器，该线程休眠
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} // while(playFrame.isVisible()) end
	}
  public void close(){
	if(playFrame != null){
		playFrame.setVisible(false);
	}
	if(sendAndReceive != null){
		sendAndReceive.close();
	}
}
	public Message analysisMessage(Message message) {
		if ((message.msg & MessageMSG.FILE) == MessageMSG.FILE) {// 收到文件的信息
			if(message.saveFile()){
				System.out.println(message.file.getFileName()+"文件成功保存");
			}
			message.order = Order.NULL;
		}
//		if ((message.msg & MessageMSG.CHAT_MSG) == MessageMSG.CHAT_MSG) {// 收到聊天信息
//			PlayFrame.showChatIntable(message.chatmsg, message.clientDataClass.getClientName());
//			message.order = Order.NULL;
//		}
		if ((message.msg &  MessageMSG.IS_BEGIN) == MessageMSG.IS_BEGIN) {
			ChessClient.setBegin(message.isBegin);
			playFrame.updateButton();
			message.order = Order.NULL;
		}
		if ((message.msg & MessageMSG.CHESS_POINT) == MessageMSG.CHESS_POINT) {
			if (PlayFrame.getCount() + 1 == message.chessNum) {
				PlayFrame.pushChessStack(message.chesspoint);
				PlayFrame.setCount(message.chessNum);
				PlayFrame.showAllChess();// 显示棋子
				if (ChessClient.getClientDataClass().getAttribute() <= 2) {
					PlayFrame.setCanPlay(true);
				}
			} else {// 棋子的数目不对
				ChessClient.askForAllChess();// 这里要求调用
			}
			message.order = Order.NULL;
		}
		if ((message.msg & MessageMSG.CHESS_ALL) == MessageMSG.CHESS_ALL) {
			if (message.chessall != null && !message.chessall.empty() || message.chessNum == 0) {
				PlayFrame.setChessStack(message.chessall);
				PlayFrame.setCount(PlayFrame.getChessStack().size());
				PlayFrame.getPanelTable().repaint();
				PlayFrame.showAllChess();
			}
			if (message.order != Order.AGREE_BACK) {
				message.order = Order.NULL;
			}
		}
		if ((message.msg & MessageMSG.CLIENTD_DATAS) == MessageMSG.CLIENTD_DATAS) {
			ChessClient.clientdataVec = message.clientDatas;
			for (ClientDataClass c : message.clientDatas) {
				if (ChessClient.getClientDataClass().equals(c)) {
					ChessClient.setClientDataClass(c);// 更新本地数据
				}
			}
			playFrame.updateUserList();
			playFrame.updateButton();
//			if (message.order != Order.SET_SERVER) {
//				message.order = Order.NULL;
//			}
		}
		return message;
	}

	public  synchronized void clientOperation(Message message) {
		String nameVSnameString;
		switch (message.order) {
		case WIN:
			ChessClient.setBegin(false);
			playFrame.updateButton();
			playFrame.showNoticeIntable(message.clientDataClass.getClientName()+"赢棋了！","通知" );
			break;
		case UPDATA_YOUSELF:
			if (ChessClient.getClientDataClass().getAttribute() == 0) {
				playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 成功加入房间 ", "通知");
				ChessClient.askForAllChess();
			}
			ChessClient.setClientDataClass(message.clientDataClass); 
			ChessClient.setUpClient();
			playFrame.updateButton();

			break;
		case JOIN:
			ChessClient.clientdataVec.add(message.clientDataClass);
			if(ChessClient.getClientDataClass().equals(message.clientDataClass)){
				ChessClient.setClientDataClass(message.clientDataClass); 
				playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 成功加入房间 ", "通知");
				ChessClient.askForAllChess();
			}else{
			playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 用户加入房间 ", "通知");
			}
			ChessClient.setUpClient();
			playFrame.updateButton();
			break;
		case CHAT:
			playFrame.showChatIntable(message.chatmsg, message.clientDataClass.getClientName());
			break;
		case SECRET_CHAT:
			playFrame.showChatIntable(message.chatmsg, message.clientDataClass.getClientName());
			break;
		case ASK_PEACE:
			CommonAction.askedForPeaceDialog();
			break;
		case BACK:
			CommonAction.askedForBackDialog();
			break;
		case GIVEUP:
			ChessClient.setBegin(false);
			playFrame.updateButton();
			playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 玩家投降了", "通知");
			if (ChessClient.getClientDataClass().getAttribute() <= 2) {
				CommonAction.otherGiveUp();
			}
			break;
		case AGREE_ASKPEACE:
			playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 玩家同意求和", "通知");
			if (ChessClient.getClientDataClass().getAttribute() <= 2) {
				CommonAction.answerForPeace(true);
			}

			break;
		case DISAGREE_ASKPEACE:
			playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 玩家不同意求和", "通知");
			if (ChessClient.getClientDataClass().getAttribute() <= 2) {
				CommonAction.answerForPeace(false);
			}
			break;
		case AGREE_BACK:
			playFrame.otherAgreeBack();
			if (ChessClient.getClientDataClass().getAttribute() <= 2) {
				PlayFrame.setCanPlay(true);
				CommonAction.answerForBack(true);
			} else {
				playFrame.showNoticeIntable(message.clientDataClass.getClientName() + "同意对方的悔棋", "通知");
			}

			break;
		case DISAGREE_BACK:
			if (ChessClient.getClientDataClass().getAttribute() <= 2) {
				if (PlayFrame.chessStack.peek().getNowPlay() == (3 - ChessClient.getAttribute())) {
					PlayFrame.setCanPlay(true);
				}
				CommonAction.answerForBack(false);
			} else {
				playFrame.showNoticeIntable(message.clientDataClass.getClientName() + "不同意对方的悔棋", "通知");
			}
			break;
		case KICK: // 被踢的人接到消息后，自己向服务器发送离开服务器的请求
			if (ChessClient.getClientDataClass().equals(message.oppClientDataClass)) {
				playFrame.showNoticeIntable(message.oppClientDataClass.getClientName() + " 您被房主请出了房间",
						"通知");
				ChessClient.kicked();
				MyDialog myDialog = new MyDialog();
				myDialog.showMessageDialog("提示", "<html>" + message.oppClientDataClass.getClientName() + "您被房主请出了房间!",
						2);
				playFrame.setVisible(false);
				if(MainWindowUI.getNetmode() == Netmode.WAN){
					((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).setVisible(true);
				}else{
					((SearchJFrameOfLAN)MainWindowUI.getSearchframe()).setVisible(true);
				}
				
			}
			break;
		case EXIT:// 通过同步服务器玩家信息来更新本地的玩家信息
			playFrame.showNoticeIntable(message.clientDataClass.getClientName() + " 玩家退出了房间", "通知");
			ChessClient.setUpClient();
			break;
		case SET_SERVER:
			MyDialog myDialog = new MyDialog();
			if(MainWindowUI.getNetmode() == Netmode.LAN){//局域网
				if(message.clientDataClass.equals(ChessClient.getClientDataClass())){// 在本地建立服务器
					ChessClient.getClientDataClass().setAttribute(1);
					if (SearchJFrameOfLAN.createServer()) {
						Socket socket = null;
						if ((socket = ChessClient.reConnectServer()) == null){
							ChessClient.exitRoom();
						}else{//在本地建立服务器成功并连接上
							this.sendAndReceive.setSocket(socket);
							ChessClient.reConect();// 测试使用
							myDialog.showMessageDialog("提示",
									"<html>" + ChessClient.getClientDataClass().getClientName() + "您已成为房主，<br>请重新开始比赛！</html>",
									1);
						}
					}
				}else{//其他客户重新连接上服务器
					try {
						Thread.sleep(3000);// 等待真正的服务器打开**************
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					Socket socket = null;
					if((socket = ChessClient.reConnectServer(message.getClientDataClass().getClientAddress())) == null){
						ChessClient.exitRoom();
					}else{
						this.sendAndReceive.setSocket(socket);
						ChessClient.reConect();// 测试使用
						myDialog.showMessageDialog("提示", "<html>抱歉，重新与服务器连接，<br>可以继续游戏……</html>", 1);
					}
				}
			} else{//广域网中直接把客户的属性改为1即可
                if(message.clientDataClass.equals(ChessClient.getClientDataClass())){
					ChessClient.getClientDataClass().setAttribute(1);
					playFrame.updateButton();
				}
			}//广域网中直接把客户的属性改为1即可 end
			break;
		case BEGIN:
			CompetitorAction.askedForBeginDialog();
			break;
		case AGREE_BEGIN:// 游戏被初始化
			ChessClient.setBegin(true); 
			ChessClient.setIDOfChess(message.IDOfChess);
			playFrame.updateButton();
			if (ChessClient.getClientDataClass().getAttribute() == 1) {// 如果是房主
				RoomOwnerAction.answerForBegin(true);
			}
			playFrame.rePlay();
			nameVSnameString = new String(
					message.clientDataClass.getClientName() + "　VS　" + message.oppClientDataClass.getClientName());
			playFrame.showNoticeIntable(nameVSnameString + "\t比赛开始", "通知");
			break;
		case DISAGREE_BEGIN:
			if (ChessClient.getClientDataClass().getAttribute() == 1) {
				RoomOwnerAction.answerForBegin(false);
			}
			break;
		case AGREE_REPLAY:
			ChessClient.setBegin(true); 
			playFrame.updateButton();
			if(message.IDOfChess != null){
				ChessClient.setIDOfChess(message.IDOfChess);
			}
			if (ChessClient.getClientDataClass().getAttribute() == 1) {// 如果是房主
				RoomOwnerAction.answerForBegin(true);
			} else if (ChessClient.getClientDataClass().getAttribute() == 2) {
				CommonAction.rePlayInformation(true);
			} else {
				playFrame.rePlay();
			}
			nameVSnameString = new String(
					message.clientDataClass.getClientName() + "　VS　" + message.oppClientDataClass.getClientName());
			playFrame.showNoticeIntable(nameVSnameString + "\t比赛开始", "通知");
			break;
		case DISAGREE_REPLAY:
			if (ChessClient.getClientDataClass().getAttribute() == 1) {// 如果是房主
				RoomOwnerAction.answerForBegin(false);
			} else if (ChessClient.getClientDataClass().getAttribute() == 2) {
				CommonAction.rePlayInformation(false);
				// //将会把本地的客户属性设为4
				// ChessClient.clientDataClass.setAttribute(4);
			}
			break;
		case SETOPP:
			ChessClient.getClientDataClass().setAttribute(2);
			playFrame.showNoticeIntable("您已成为对手", "通知");
			break;
		default:
			break;
		}

	}
}
